import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { RouteRecordRaw } from 'vue-router'
import type { RouteRecord } from '@/types/route'
import router from '@/router'
import { ElMessage } from 'element-plus'

export const useRouteStore = defineStore('route', () => {
  const routes = ref<RouteRecord[]>([])

  // 将路由配置转换为路由记录
  function transformRoute(route: RouteRecordRaw, parentPath = ''): RouteRecord {
    const fullPath = parentPath ? `${parentPath}/${route.path}`.replace(/\/+/g, '/') : route.path
    const componentPath = typeof route.component === 'function' 
      ? route.component.toString().split('import("')[1]?.split('")')[0] || 'Unknown'
      : 'Unknown'
    
    return {
      title: route.meta?.title as string || route.name as string || '',
      path: fullPath,
      component: componentPath.replace('@/', ''),
      icon: route.meta?.icon as string || '',
      sort: route.meta?.sort as number || 0,
      hidden: route.meta?.hidden as boolean || false,
      children: route.children?.map(child => transformRoute(child, fullPath)) || []
    }
  }

  // 初始化路由数据
  function initRoutes() {
    const systemRoutes = router.options.routes
      .filter(route => !['Login', 'Error', 'NotFound'].includes(route.name as string))
      .map(route => transformRoute(route))
    
    routes.value = systemRoutes
  }

  // 更新路由
  async function updateRoute(route: RouteRecord) {
    try {
      // 找到并更新路由
      const updateRouteInTree = (routes: RouteRecord[], route: RouteRecord): boolean => {
        for (let i = 0; i < routes.length; i++) {
          if (routes[i].path === route.path) {
            routes[i] = { ...routes[i], ...route }
            return true
          }
          if (routes[i].children?.length) {
            if (updateRouteInTree(routes[i].children, route)) {
              return true
            }
          }
        }
        return false
      }

      if (updateRouteInTree(routes.value, route)) {
        // TODO: 调用后端 API 更新路由
        ElMessage.success('路由更新成功')
        return true
      }
      throw new Error('未找到要更新的路由')
    } catch (error) {
      console.error('Update route failed:', error)
      ElMessage.error('路由更新失败')
      return false
    }
  }

  // 添加路由
  async function addRoute(route: RouteRecord, parentPath?: string) {
    try {
      if (parentPath) {
        // 添加子路由
        const addChildRoute = (routes: RouteRecord[], parentPath: string, newRoute: RouteRecord): boolean => {
          for (let i = 0; i < routes.length; i++) {
            if (routes[i].path === parentPath) {
              routes[i].children = routes[i].children || []
              routes[i].children.push(newRoute)
              return true
            }
            if (routes[i].children?.length) {
              if (addChildRoute(routes[i].children, parentPath, newRoute)) {
                return true
              }
            }
          }
          return false
        }

        if (addChildRoute(routes.value, parentPath, route)) {
          // TODO: 调用后端 API 添加路由
          ElMessage.success('子路由添加成功')
          return true
        }
        throw new Error('未找到父路由')
      } else {
        // 添加顶级路由
        routes.value.push(route)
        // TODO: 调用后端 API 添加路由
        ElMessage.success('路由添加成功')
        return true
      }
    } catch (error) {
      console.error('Add route failed:', error)
      ElMessage.error('路由添加失败')
      return false
    }
  }

  // 删除路由
  async function deleteRoute(path: string) {
    try {
      // 递归删除路由
      const deleteRouteFromTree = (routes: RouteRecord[], path: string): boolean => {
        for (let i = 0; i < routes.length; i++) {
          if (routes[i].path === path) {
            routes.splice(i, 1)
            return true
          }
          if (routes[i].children?.length) {
            if (deleteRouteFromTree(routes[i].children, path)) {
              return true
            }
          }
        }
        return false
      }

      if (deleteRouteFromTree(routes.value, path)) {
        // TODO: 调用后端 API 删除路由
        ElMessage.success('路由删除成功')
        return true
      }
      throw new Error('未找到要删除的路由')
    } catch (error) {
      console.error('Delete route failed:', error)
      ElMessage.error('路由删除失败')
      return false
    }
  }

  return {
    routes,
    initRoutes,
    updateRoute,
    addRoute,
    deleteRoute
  }
}) 